package com.efeichong.common.security;

import com.efeichong.oss.OssConfigLocal;
import com.efeichong.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @author lxk
 * @date 2020/9/2
 * @description Security配置
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    SecurityIgnoreConfig securityIgnoreConfig;
    @Autowired
    private OssConfigLocal ossConfigLocal;
    @Value("${knife4j.enable:false}")
    private boolean enableOpenApi;

    @Override
    public void configure(WebSecurity web) {
        WebSecurity.IgnoredRequestConfigurer ignoredRequestConfigurer = web.ignoring();
        if (enableOpenApi) {
            ignoredRequestConfigurer.antMatchers("/doc.html")
                    //swagger资源文件加载
                    .antMatchers("/swagger-ui/*")
                    .antMatchers("/swagger-resources/**")
                    .antMatchers("/v2/api-docs")
                    .antMatchers("/v3/api-docs")
                    .antMatchers("/webjars/**");
        }
        ignoredRequestConfigurer.antMatchers("/error")
                .antMatchers("/favicon.ico")
                .antMatchers("/process/**");
        if (ossConfigLocal != null) {
            String viewUrlPrefix = ossConfigLocal.getViewUrlPrefix();
            ignoredRequestConfigurer.antMatchers("/" + trimBothChars(viewUrlPrefix, "/") + "/**");
        }
        //配置不需要保护的访问
        for (String path : securityIgnoreConfig.getIgnoreAll()) {
            ignoredRequestConfigurer.antMatchers(path);
        }
    }

    /**
     * 去掉字符串前后的指定字符
     */
    private String trimBothChars(String str, String splitter) {
        if (EntityUtils.isEmpty(str)) {
            return "";
        }
        String regex = "^" + splitter + "*|" + splitter + "*$";
        return str.replaceAll(regex, "");
    }


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors()
                .and()
                // CRSF禁用，因为不使用session
                .csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                .anyRequest().access("@securityUtil.access(request, authentication)")
                .and()
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler())
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                .and()
                .headers().frameOptions(frameOptions -> frameOptions.sameOrigin());
        // 添加JWT filter
        httpSecurity.addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
        return new RestfulAccessDeniedHandler();
    }

    @Bean
    public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
        return new RestAuthenticationEntryPoint();
    }
}
